<template>
  <el-table :data="userArr">
    <el-table-column label="编号" type="index"></el-table-column>
    <el-table-column label="用户名" prop="username"></el-table-column>
    <el-table-column label="昵称" prop="nickname"></el-table-column>
    <el-table-column label="头像">
      <template slot-scope="scope">
        <el-avatar :src="BASE_URL+scope.row.imgUrl"></el-avatar>
      </template>
    </el-table-column>
    <el-table-column label="管理员">
      <template slot-scope="scope">
        <el-switch @change="handleChange(scope.row)" v-model="scope.row.isAdmin"></el-switch>
      </template>
    </el-table-column>
    <el-table-column label="创建时间" prop="createTime"></el-table-column>
    <el-table-column label="操作">
      <template slot-scope="scope">
        <el-button type="danger"
                   @click="handleDelete(scope.$index,scope.row)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>
</template>

<script>
export default {
  name: "AdminIndexView",
  data() {
    return {
      userArr:[],
    }
  },
  methods: {
    handleChange(user){
      //准备请求的数据 包含用户id和是否是管理员
      let u = {id:user.id,isAdmin:user.isAdmin?1:0};
      let data = this.qs.stringify(u);
      this.axios.post(this.BASE_URL+'/v1/users/change',data)
          .then((response)=>{
            if (response.data.code==1){
              if (user.isAdmin){
                this.$message.success('设置'+user.nickname+'为管理员!');
              }else{
                this.$message.success('取消'+user.nickname+'的管理员状态!');
              }
            }
          })
    },
    handleDelete(i,user) {
      if (confirm('您确认删除此用户吗?')){
        this.axios.post(this.BASE_URL+'/v1/users/'+user.id+'/delete')
            .then((response)=>{
              if (response.data.code==1){
                this.userArr.splice(i,1);
              }
            })
      }
    }
  },
  mounted() {
    //请求用户列表
    this.axios.get(this.BASE_URL+'/v1/users/').then((response)=>{
      if (response.data.code==1){
        this.userArr = response.data.data;
      }
    })
  }
}
</script>

<style scoped>

</style>